package com.yaoxun.quartz.service.impl;

import javax.validation.ValidationException;

import org.quartz.Scheduler;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import com.yaoxun.quartz.domain.entity.ScheduleJob;
import com.yaoxun.quartz.domain.vo.AddScheduleJob;
import com.yaoxun.quartz.domain.vo.DelScheduleJob;
import com.yaoxun.quartz.domain.vo.UpdateScheduleJob;
import com.yaoxun.quartz.service.ScheduleJobService;
import com.yaoxun.quartz.util.ScheduleUtils;

@Service
public class ScheduleJobServiceImpl implements ScheduleJobService {

	@Autowired
	private ApplicationContext applicationContext;
	
	@Autowired
	private Scheduler scheduler;
	
	@Override
	public void add(AddScheduleJob addScheduleJob) {
		existBeanName(addScheduleJob.getBeanName());
		ScheduleJob scheduleJob = new ScheduleJob();
		BeanUtils.copyProperties(addScheduleJob, scheduleJob);
		ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
	}

	private void existBeanName(String beanName) {
		boolean containsBean = applicationContext.containsBean(beanName);
		if(!containsBean) {
			throw new ValidationException("beanName can not fond in contaner");
		}
	}
	
	@Override
	public void update(UpdateScheduleJob updateScheduleJob) {
		existBeanName(updateScheduleJob.getBeanName());
		ScheduleJob scheduleJob = new ScheduleJob();
		BeanUtils.copyProperties(updateScheduleJob, scheduleJob);
		ScheduleUtils.updateScheduleJob(scheduler, scheduleJob);
	}

	@Override
	public void delete(DelScheduleJob delScheduleJob) {
		ScheduleUtils.deleteJob(scheduler, delScheduleJob.getJobId());
	}

	
}
